package pnu.ssm.sbmother;

import java.util.*;

import pnu.ssm.appinfo.*;
import pnu.ssm.http.*;
import pnu.ssm.key.*;
import android.app.*;
import android.content.*;
import android.os.*;
import android.preference.*;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.util.*;
import android.view.*;
import android.widget.*;

public class SettingActivity extends PreferenceActivity implements OnPreferenceChangeListener, OnPreferenceClickListener {
	public static final String TAG = "SettingActivity";

	public static final String LOGIN_KEY = "setting_login";
	public static final String CHILDREN_CATEGORY_KEY = "setting_children_category";
	public static final String TIMER_KEY = "setting_timer_value";

	private Preference mLogin;
	private EditTextPreference mTimer;
	
	private List<Child> mChildrenList;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.layout.activity_setting);

		initializePreference();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		ActionBar actionBar = getActionBar();
		actionBar.setTitle("설정");
		actionBar.setHomeButtonEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(true);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch(item.getItemId()) {
		case android.R.id.home :
			finish();
		}

		return super.onMenuItemSelected(featureId, item);
	}

	@SuppressWarnings("deprecation")
	private void initializePreference() {
		mLogin = findPreference(LOGIN_KEY);
		mTimer = (EditTextPreference)findPreference(TIMER_KEY);

		PrefListener listener = new PrefListener();
		
		mLogin.setOnPreferenceClickListener(listener);
		mTimer.setOnPreferenceChangeListener(this);
		
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

		String value = pref.getString(TIMER_KEY, "1");
		mTimer.setText(value);
		
		PreferenceInitAsyncTask task = new PreferenceInitAsyncTask();
		task.execute();
	}

	@Override
	public boolean onPreferenceClick(Preference p) {
		if(mChildrenList == null)
			return false;

		for(Child c : mChildrenList) {
			if(p.getKey().equals(c.hashCode() + "")) {
				showChildDeleteDialog(c, p);
				break;
			}
		}
		
		return false;
	}
	
	private void showChildDeleteDialog(final Child c, final Preference p) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this)
		.setTitle(c.getChildName() + "님을 해제할까요 ?")
		.setCancelable(true)
		.setPositiveButton("확인", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				ChildPairingDeleteAsyncTask task = new ChildPairingDeleteAsyncTask(c, p);
				task.execute();
			}
		})
		.setNegativeButton("취소", null);
		
		builder.create().show();
	}
	
	private void showLogoutDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this)
		.setTitle("로그아웃 할까요 ?")
		.setCancelable(true)
		.setPositiveButton("확인", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				SharedPreferences pref = getSharedPreferences(Key.prefKey, Context.MODE_PRIVATE);
				SharedPreferences.Editor edit = pref.edit();
				edit.putString(Key.parent_num, "");
				edit.commit();
				Toast.makeText(getApplicationContext(), "로그아웃 하였습니다.", Toast.LENGTH_LONG).show();
				
				Intent activity = new Intent(getApplicationContext(), LoginActivity.class);
				activity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(activity);
			}
		})
		.setNegativeButton("취소", null);
		
		builder.create().show();
	}

	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue) {
		Log.e(TAG, newValue.toString());
		
		EditTextPreference ep = (EditTextPreference)preference;
		ep.setText((String)newValue);
		
		return false;
	}

	private class PrefListener implements OnPreferenceClickListener {
		@Override
		public boolean onPreferenceClick(Preference preference) {
			if(preference.getKey().equals(LOGIN_KEY)) {
				showLogoutDialog();
			}
			
			return false;
		}
	}
	
	private class ChildPairingDeleteAsyncTask extends AsyncTask<Void, Void, Void> {
		public static final String TAG = "ChildPairingDeleteAsyncTask";
		
		private Child mChild;
		private String mParentNum;
		private Preference mPref;
		private ProgressDialog mDialog;
		
		public ChildPairingDeleteAsyncTask(Child c, Preference p) {
			this.mChild = c;
			
			SharedPreferences pref = getSharedPreferences(Key.prefKey, Context.MODE_PRIVATE);
			mParentNum = pref.getString(Key.parent_num, "");
			mPref = p;
			
			mDialog = new ProgressDialog(SettingActivity.this);
			mDialog.setMessage("해제중입니다...");
			mDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			HttpConnectorParent parent = HttpConnectorParent.getInstance();
			String re = parent.deleteChild(mParentNum, mChild.getChildName());
			
			if(re == null)
				Log.e(TAG, "null");
			else
				Log.e(TAG, re);
			
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			PreferenceCategory category = (PreferenceCategory)findPreference(CHILDREN_CATEGORY_KEY);
			category.removePreference(mPref);
			Toast.makeText(getApplicationContext(), "성공적으로 해제하였습니다.", Toast.LENGTH_LONG).show();
			mDialog.dismiss();
			
			Intent activity = new Intent(getApplicationContext(), SelectActivity.class);
			activity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(activity);
		}
	}

	private class PreferenceInitAsyncTask extends AsyncTask<Void, Void, List<Preference>> {
		private HttpConnectorParent mParent;
		private String mParentNum;

		public PreferenceInitAsyncTask() {
			SharedPreferences pref = getSharedPreferences(Key.prefKey, Context.MODE_PRIVATE);
			mParentNum = pref.getString(Key.parent_num, "");
		}

		@Override
		protected List<Preference> doInBackground(Void... arg0) {
			mParent = HttpConnectorParent.getInstance();
			List<Child> list = mParent.getChildList(mParentNum);
			List<Preference> pList = new ArrayList<Preference>(list.size());
			
			mChildrenList = list;

			for(Child c : list) {
				Preference p = new Preference(SettingActivity.this);
				p.setTitle(c.getChildName());
				p.setSummary(c.getChildType());
				p.setKey(c.hashCode() + "");

				pList.add(p);
			}

			return pList;
		}

		@Override
		protected void onPostExecute(List<Preference> result) {
			PreferenceCategory category = (PreferenceCategory)findPreference(CHILDREN_CATEGORY_KEY);
			
			for(Preference p : result) {
				p.setOnPreferenceClickListener(SettingActivity.this);
				category.addPreference(p);
			}
		}
	}
}
